import React, { Component } from 'react';
import findIndex from 'lodash/findIndex';
import Picker from '../Picker/Picker';
class DatePicker extends Component {
    static defaultProps = {
        onMaskClick: () => {},
        startTime: '',
        endTime: '',
        defaultSelected: ''
    };
    constructor(props) {
        super(props);
        this.initData = this.initData.bind(this);
        this.getSelectedIndex = this.getSelectedIndex.bind(this);
        this.getYearData = this.getYearData.bind(this);
        this.getMouthData = this.getMouthData.bind(this);
        this.getDayData = this.getDayData.bind(this);
        this.getHoursData = this.getHoursData.bind(this);
        this.getMinuteData = this.getMinuteData.bind(this);
        this.draw = this.draw.bind(this);
        const toDay = new Date();
        const day = toDay.getDate();
        const mouth = toDay.getMonth() + 1;
        const year = toDay.getFullYear();
        const defaultSelected =
            props.defaultSelected && props.defaultSelected.split('-');
        this.startTime = props.startTime.split('-');
        this.endTime = props.endTime.split('-');
        this.state = {
            selected: defaultSelected || [
                `${year}年`,
                `${mouth}月`,
                `${day}日`,
                '0时',
                '0分'
            ],
            cacheSelect: defaultSelected.slice(0, 2) || [
                `${year}年`,
                `${mouth}月`
            ],
            yearData: '',
            dayData: '',
            mouthData: '',
            hoursData: '',
            minuteData: ''
        };
    }

    initData() {
        const yearData = this.getYearData().map((item, i) => ({
            text: `${item}年`
        }));
        const mouthData = this.getMouthData().map((item, i) => ({
            text: `${item}月`
        }));
        const dayData = this.getDayData().map((item, i) => ({
            text: `${item.date}日`
        }));
        const hoursData = this.getHoursData().map((item, i) => ({
            text: `${item}时`
        }));
        const minuteData = this.getMinuteData().map((item, i) => ({
            text: `${item}分`
        }));

        this.setState({ yearData, dayData, mouthData, hoursData, minuteData });
    }

    componentWillMount() {
        this.initData();
    }

    componentWillReceiveProps() {
        this.initData();
    }

    getSelectedIndex() {
        const {
            selected,
            yearData,
            dayData,
            mouthData,
            hoursData,
            minuteData
        } = this.state;
        const ssData = [yearData, dayData, mouthData, hoursData, minuteData];
        console.log(selected);
        let res = [];
        selected.forEach((item, i) => {
            ssData.forEach((ss, k) => {
                let index = findIndex(ss, ssx => {
                    return ssx.text == item;
                });
                if (index !== -1) {
                    res.push(index);
                }
            });
        });
        return res;
    }

    getYearData() {
        const nowDay = new Date();
        const year = nowDay.getFullYear();
        const sTime = this.startTime[0];
        const eTime = this.endTime[0];
        let res = [];
        for (let i = sTime || year - 100; i <= (eTime || year + 100); i++) {
            res.push(i);
        }
        return res;
    }

    getMouthData() {
        let sTime = 0;
        let eTime = 12;
        const yearData = parseInt(this.state.cacheSelect[0]);
        if (this.startTime[0] == yearData) {
            sTime = this.startTime[1] - 1;
        }
        if (this.endTime[0] == yearData) {
            eTime = this.endTime[1];
        }
        let res = [];
        do {
            sTime++;
            res.push(sTime);
        } while (sTime < eTime);
        return res;
    }

    getDayData() {
        const selectYearData = parseInt(this.state.cacheSelect[0]);
        const selectMouthData = parseInt(this.state.cacheSelect[1]);
        let data = this.draw(selectYearData, selectMouthData);
        const yearData = parseInt(this.state.cacheSelect[0]);
        const mouthData = parseInt(this.state.cacheSelect[1]);
        if (this.startTime[0] == yearData && this.startTime[1] == mouthData) {
            data.splice(0, this.startTime[2] - 1);
        }
        if (this.endTime[0] == yearData && this.endTime[1] == mouthData) {
            data = data.slice(0, this.endTime[2]);
        }
        return data;
    }

    getHoursData() {
        const { hoursType = '24' } = this.props;
        let res = [];
        for (let i = 0; i < hoursType; i++) {
            res.push(i);
        }
        return res;
    }

    getMinuteData() {
        let res = [];
        for (let i = 0; i < 60; i++) {
            res.push(i);
        }
        return res;
    }

    dateColChange(item, i, type, num) {
        if (type === 'year' || type === 'month') {
            const { cacheSelect } = this.state;
            cacheSelect[num] = item.text;
            this.setState({ cacheSelect }, () => {
                const yearData = this.getYearData().map((item, i) => ({
                    text: `${item}年`
                }));
                const mouthData = this.getMouthData().map((item, i) => ({
                    text: `${item}月`
                }));
                const dayData = this.getDayData().map((item, i) => ({
                    text: `${item.date}日`
                }));
                this.setState({ yearData, mouthData, dayData });
            });
        }
    }

    draw(year, month) {
        // 当月第一天是周几
        let toMonthFirWeek = new Date(year, month, 1).getDay();
        // 当月总共多少天
        const toMonthAllDay = new Date(year, month, 0).getDate();
        // 行数
        const bodyLine = Math.ceil((toMonthAllDay + toMonthFirWeek) / 7);
        const days = [];
        for (let i = 0; i < bodyLine; i++) {
            for (let k = 0; k < 7; k++) {
                const idx = i * 7 + k;
                let date = String(idx - toMonthFirWeek + 1);
                if (date > 0 && date <= toMonthAllDay) {
                    days.push({
                        date
                    });
                }
            }
        }
        return days;
    }

    onOk(item) {
        const selected = item.map((m, i) => m.item.text);
        this.setState({ selected });
        this.props.onOk(item);
    }

    render() {
        const {
            show,
            title,
            onCancel,
            onOk,
            onMaskClick,
            colChange,
            mode = 'date'
        } = this.props;
        const {
            yearData,
            dayData,
            mouthData,
            hoursData,
            minuteData
        } = this.state;
        const de = this.getSelectedIndex();
        // 日期选择的类型, 可以是日期date,时间time,日期+时间datetime,年year,月month
        const typeMode = (mode, type) => {
            if (
                mode === 'datetime' ||
                (mode === 'date' && type !== 'hours' && type !== 'minute') ||
                mode === type
            ) {
                return true;
            }
        };

        return (
            <div>
                <Picker
                    show={show}
                    onCancel={() => onCancel()}
                    onOk={item => this.onOk(item)}
                    onMaskClick={() => onMaskClick()}
                    cascade={false}
                >
                    {typeMode(mode, 'year') ? (
                        <Picker.PickerColumn
                            data={yearData}
                            colChange={(item, i) =>
                                this.dateColChange(item, i, 'year', 0)
                            }
                            defaultIndex={de[0]}
                        />
                    ) : null}
                    {typeMode(mode, 'month') ? (
                        <Picker.PickerColumn
                            data={mouthData}
                            colChange={(item, i) =>
                                this.dateColChange(item, i, 'month', 1)
                            }
                            defaultIndex={de[1]}
                        />
                    ) : null}
                    {typeMode(mode, 'day') ? (
                        <Picker.PickerColumn
                            data={dayData}
                            colChange={(item, i) =>
                                this.dateColChange(item, i, 'day', 2)
                            }
                            defaultIndex={de[2]}
                        />
                    ) : null}
                    {typeMode(mode, 'hours') ? (
                        <Picker.PickerColumn
                            data={hoursData}
                            colChange={(item, i) =>
                                this.dateColChange(item, i, 'hours', 3)
                            }
                            defaultIndex={de[3]}
                        />
                    ) : null}
                    {typeMode(mode, 'minute') ? (
                        <Picker.PickerColumn
                            data={minuteData}
                            colChange={(item, i) =>
                                this.dateColChange(item, i, 'minute', 4)
                            }
                            defaultIndex={de[4]}
                        />
                    ) : null}
                </Picker>
            </div>
        );
    }
}

export default DatePicker;
